// pages/00login/login.js
var app = getApp()
var appData = app.globalData
var co = require('../js/common.js')
var M = require('../js/md5.js')
var wss_init = 0
Page({
   data: {
      isShowInputLabelArr: [0, 0, 0],
      pxArrShow: [0, 0, 0, 0, 0],
      pxArr: [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
      shopInfo: '',
      loginBossInfo: '',
      loginWaiterInfo: '',
      loginGuestInfo: '',
      loginMode: 'guest',
      isNewGuest: '',
      tableInfo: '',
      order: '',
      setGuestNumShow: 0,//自定义弹窗参数
      regShow: 0,
      regInputShow: 0,
      numArray: [
         [1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12],
         [13, 14, 15, 0]],
      inviter: ''
      //testImg: "../images/qzg_logo_90x_dark.jpg"  
   },

   // errImg: function (e) {
   //     var _errImg = e.target.dataset.errImg;
   //     var _objImg = "'" + _errImg + "'";
   //     var _errObj = {};
   //     _errObj[_errImg] = "../images/qzg_logo_90x_dark.jpg";
   //     console.log(e.detail.errMsg + "----" + _errObj[_errImg] + "----" + _objImg);
   //     this.setData(_errObj);//注意这里的赋值方式...  
   // },

   onLoad: function (opt) {
      if (opt) {
         if (opt.hasOwnProperty('str')) {
            var obj = JSON.parse(opt.str)
            this.setData({ inviter: obj })
         }
      }

      var res = wx.getSystemInfoSync()
      this.setData({
         win_w: res.windowWidth - 60,
         win_h: res.windowHeight
      })

      this.wxLogin()
      this.getBossLoginInfo()
      this.getWaiterLoginInfo()

      var t = this
      app.setNoticeTicket(function (notice) {
         console.log('顾客点完菜通知桌号小票===', notice)
         t.getTableInfo(notice)
      })
   },

   wxLogin: function () {
      if (wx.showLoading) {
         wx.showLoading({ title: '加载中…' })
      } else {
         app.toast('加载中…(您微信未升级最新版)')
      }
      var t = this
      wx.login({
         success: function (res) {
            console.log('wx.login成功:res', res)
            t.loginQzg(res.code)
         },
         fail: function (res) {
            console.log('wx.login失败:res', res)
         },
      })
   },
   //微信识别登录
   loginQzg: function (code) {
      var param = {
         code: code,
         appid: 'wxd8fd206ea9db41e4',
         secret: 'fa0b483bd89aa9f14688d4f237efda00',
      }
      var t = this
      app.getNetData('member/manage/wxlogin', param, function (res) {
         if (wx.hideLoading) wx.hideLoading()
         var rd = res.data
         t.setData({
            loginGuestInfo: rd,
            isNewGuest: res.code == 0 ? 0 : 1
         })
         appData.guestInfo = rd

         if (res.code == 0) t.getUserOrder(rd.userid)

         console.log('微信识别登录==', t.data)
      })
   },

   getUserOrder: function (userid) {
      var param = { userid: userid }
      var t = this
      app.getNetData('member/manage/getmemberorder', param, function (res) {
         var d = res.data
         var t_d = t.data
         if (!co.isEmpty(d.shopInfo)) {
            var s = { shopInfo: d.shopInfo }
            t.setData({ shopInfo: s })
            appData.shopInfo = s
         }
         if (!co.isEmpty(d.order)) {
            t.setData({ order: d.order })
            t.initWebsocket()
         }
         console.log('获取用户订单==', t.data)
      })
   },
   //扫描桌码
   scan: function (e) {
      var t_d = this.data
      if (t_d.isNewGuest == 0) {
         if (co.isEmpty(t_d.tableInfo)) {
            this.scanCode()
            return
         }
         if (t_d.tableInfo.status == 1) {//status==2的情况好像可以不用考虑
            this.setData({ setGuestNumShow: 1 })
         }
      } else {
         if (co.isEmpty(t_d.inviter)) {
            this.scanCode()
            return
         }
         if (t_d.inviter.hasOwnProperty('userid')) {
            this.setData({ regShow: 1 })
         }
      }
   },

   scanCode: function () {
      this.setData({
         setGuestNumShow: 0,
         regShow: 0
      })
      var t = this
      wx.scanCode({
         onlyFromCamera: true,
         success: function (res) {
            var strArr = res.result.split('=')
            t.getTableInfo(strArr[2])
         },
         fail: function (res) { },
      })
   },
   //获取桌号对应订单信息
   getTableInfo: function (tableId) {
      var param = { zhuo: tableId }
      var t = this
      app.getNetData('table/manage/getshoptableinfo', param, function (res) {
         var d = res.data
         var s = { shopInfo: d.shopInfo }
         t.setData({ shopInfo: s })
         appData.shopInfo = s

         if (t.data.inviter == '') {
            t.setData({ inviter: d.shopInfo })
         }
         delete d.shopInfo
         t.setData({ tableInfo: d })
         if (t.data.isNewGuest == 1) {
            t.setData({ regShow: 1 })//弹出注册
         } else {
            t.order(d)
         }
         console.log('获取桌信息后 t.data', t.data)
      })
   },
   //注册用户
   reg: function (urlEnd, userInfo) {
      var td = this.data
      userInfo.unionid = td.loginGuestInfo.unionid
      userInfo.rcduid = td.inviter.userid ? td.inviter.userid : td.shopInfo.shopInfo.userid
      var t = this
      app.getNetData(urlEnd, userInfo, function (res) {
         if (res.code == 0) {
            t.setData({
               loginGuestInfo: res.data,
               isNewGuest: 0,
               regShow: 0
            })
            t.order(t.data.tableInfo, 0)
            console.log('注册成功后 t.data', t.data)
         }
      })
   },

   order: function (d) {
      if (!appData.wssIsInit && !co.isEmpty(this.data.shopInfo)) {
         this.initWebsocket()
      }
      if (d.status == 2) {
         this.setData({ order: d })
      } else if (d.status == 1) {
         this.setData({ setGuestNumShow: 1 })
      } else {
         this.setData({ tableInfo: '' })
         if (d.status == 3) {
            app.modal('您刚扫描的' + d.fenlei + d.zhuo + '有人预订了')
         } else if (d.status == 0) {
            app.modal('您刚扫描的' + d.fenlei + d.zhuo + '关桌了，请咨询服务员')
         }
      }
      console.log('order:后 this.data', this.data)
   },

   //扫描桌码得到店铺信息后方能启动
   initWebsocket: function () {
      var t = this
      app.readyWebsocket(function (callback) {
         console.log('初始化Websocket_回调值callback===' + callback)
         if (callback == 'initWebsocket_ok') {
            appData.wssIsInit = 1
            t.onSocketMsg()
         }
      })
   },

   onSocketMsg: function () {
      var t = this
      wx.onSocketMessage(function (res) {
         var data = JSON.parse(res.data)
         console.log('收到服务器消息转化成对象后：', data)
         if(data.type == 'login'){
            appData.isLoginWss = 1
            console.log('登录wss成功：')
         }
         if (data.notice) {
            var N = JSON.parse(data.notice)
            console.log('全局appData.isWsSender前==', appData.isWsSender)
            if (N.msg[0] == t.data.order.id) {//是本桌才处理
               if (N.msg[1] == 1) {
                  t.setData({
                     order: '',
                     tableInfo: ''
                  })
               }
               if (appData.isWsSender == 0) {
                  t.getUserOrder(t.data.loginGuestInfo.userid)
                  app.playMp3(0)
               } else {
                  appData.isWsSender = 0
               }
            }
            console.log('全局appData.isWsSender后==', appData.isWsSender)
         }
      })
   },

   getWxOpenInfo: function () {
      var t = this
      wx.getUserInfo({
         withCredentials: true,
         success: function (res) {
            console.log('UserInfo==', res)
            t.reg('member/manage/regwxinfo', res.userInfo)
            console.log('t.data.loginGuestInfo==', t.data.loginGuestInfo)
         },
         fail: function (res) {
            console.log('fail:UserInfo==', res)
         },
      })
   },

   inputReg: function (e) {
      if (this.data.regInputShow) {
         var e_v = e.detail.value
         if (e_v.re_pass != e_v.pass) app.toast('两次输入密码不一样!')
         else {
            e_v.password = M.md5(e_v.pass)
            delete e_v.re_pass
            delete e_v.pass
            this.reg('member/manage/reg', e_v)
         }
      } else {
         this.setData({ regInputShow: 1 })
      }
   },
   //加菜
   addFood: function () {
      let tableStr = JSON.stringify(this.data.order)
      wx.navigateTo({
         url: '/pages/01homePage/02openTable/openTable?table=' + tableStr
      })
   },

   checkout: function () {
      app.toast('开发中……敬请期待！')
   },

   showRegLabel: function (e) {
      console.log('注册输入框e==', e)
      var l = e.detail.value.length
      if (l > 1) return;
      var index = e.currentTarget.id;
      var isShowArray = this.data.pxArrShow;
      isShowArray[index] = l ? 1 : 0;

      var pxArr = this.data.pxArr
      if (pxArr[index][0] == 0) {
         pxArr[index] = [(this.data.win_w + 60) * 0.1 + 25, this.data.win_h * 0.2 + e.target.offsetTop - 6]
         this.setData({ pxArr: pxArr })
      }
      this.setData({ pxArrShow: isShowArray })
   },

   showInputLabel: function (e) {
      if (e.detail.value.length > 1) return;
      var index = e.currentTarget.id;
      var isShowArray = this.data.isShowInputLabelArr;
      isShowArray[index] = 1;
      this.setData({
         isShowInputLabelArr: isShowArray
      })
   },

   getWaiterLoginInfo: function () {
      var waiterInfo = wx.getStorageSync('waiterInfo')
      if (waiterInfo) {
         this.setData({
            isShowInputLabelArr: [true, true, true],
            loginWaiterInfo: waiterInfo
         })
      }
   },

   getBossLoginInfo: function () {
      var bossInfo = wx.getStorageSync('userInfo')
      if (bossInfo) {
         this.setData({
            isShowInputLabelArr: [true, true],
            loginBossInfo: bossInfo
         })
      }
   },

   maskHide: function () {
      this.setData({
         setGuestNumShow: 0,
         regShow: 0
      })
   },
   //设置人数
   setGuestNum: function (e) {
      var num = e.currentTarget.id
      if (num > 0) {
         this.setData({ setGuestNumShow: 0 })
         var tab = this.data.tableInfo
         tab.guestNum = num
         var str = JSON.stringify(tab)
         wx.navigateTo({
            url: '/pages/01homePage/02openTable/openTable?table=' + str
         })
      } else {
         this.reSetNum(num)
      }
   },
   //重设数字
   reSetNum: function (num) {
      var nA = this.data.numArray
      for (var i = 0; i < nA.length; i++) {
         var nA2 = nA[i]
         for (var j = 0; j < nA2.length; j++) {
            if (num == 0) {
               if (nA[i][j] == 15) nA[i][j] = -1
               else if (nA[i][j] > 15) nA[i][j] += 14
               else if (nA[i][j] > 0) nA[i][j] += 15
            } else {
               if (nA[i][j - 1] == 14) nA[i][j] = 15
               else if (nA[i][j] > 29) nA[i][j] -= 14
               else if (nA[i][j] > 0) nA[i][j] -= 15
            }
         }
      }
      this.setData({ numArray: nA })
   },

   //切换登录模式
   toggleLogin: function (e) {
      var mode = ['guest', 'waiter', 'boss']
      var i = e.currentTarget.id
      this.setData({ loginMode: mode[i] })
      app.globalData.loginMode = mode[i]
   },
   //掌柜绑定+登录(接口会处理，已绑定过的直接登录，未绑定的先验证登录且绑定)
   submitLoginInfo: function (e) {
      console.log('提交的掌柜信息e：', e)
      var e_d = e.detail
      var param = e_d.value
      wx.setStorageSync('userInfo', param)
      if (param.pass != '') {
         param.pass = M.md5(param.pass)
      }
      param.unionid = this.data.loginGuestInfo.unionid
      var urlEnd = e_d.target.id == 'wx' ? 'BindLogin' : 'login'
      var t = this
      app.getNetData('shop/manage/boss' + urlEnd, param, function (res) {
         var r_d = res.data
         appData.shopInfo = r_d
         appData.guestInfo = r_d
         console.log('appData', appData)
         if (res.code == 0) {
            t.goto(r_d.shop_id)
         }
         if (res.code == 81) {
            app.toast(res.msg)
            setTimeout(function () {
               t.goto(r_d.shop_id)
            }, 1500)
         }
         if (res.code == 92900) {
            app.toast(res.msg)
         }
      })
   },

   //服务员绑定+登录(接口会处理，已绑定过的直接登录，未绑定的先验证登录且绑定)
   submitWaiterInfo: function (e) {
      app.readyWebsocket()

      console.log('提交的服务员信息e：', e)
      var e_d = e.detail
      var param = e_d.value
      wx.setStorageSync('waiterInfo', param)
      param.unionid = this.data.loginGuestInfo.unionid
      var t = this
      var urlEnd = e_d.target.id == 'wx' ? 'BindLogin' : 'login'
      app.getNetData('shop/manage/waiter' + urlEnd, param, function (res) {
         var r_d = res.data
         appData.shopInfo = r_d
         appData.guestInfo = r_d
         if (res.code == 0) {
            t.goto(r_d.shop_id)
         }
         if (res.code == 81) {
            app.toast(res.msg)
            setTimeout(function () { t.goto(r_d.shop_id) }, 1500)
         }
         if (res.code == 92900) {
            app.toast(res.msg)
         }
      })
   },

   goto: function (shop_id) {
      wx.switchTab({
         url: '/pages/01homePage/01home/home?userid=' + shop_id
      })
   },

   onPullDownRefresh: function () {
      this.reload('下')
   },

   onReachBottom: function () {
      this.reload('上')
   },

   reload: function (msg) {
      app.toast(msg + '拉刷新了')
      this.onLoad()
      this.setData({
         order: '',
         tableInfo: ''
      })
   },

   onShareAppMessage: function () {
      var userInfoStr = JSON.stringify(this.data.loginGuestInfo)
      return {
         title: this.data.loginGuestInfo.name + '邀请您来【桥掌柜】当掌柜',
         path: '/pages/00login/login?str=' + userInfoStr
      }
   }
})
